import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'common_colors.dart';
import 'common_utils.dart';
import 'data/article_comment_entity.dart';
import 'data/article_entity.dart';
import 'data/article_extra_entity.dart';

class ArticleDetail extends StatefulWidget {
  ArticleDetail(
    this.articleEntity,
  );

  ArticleEntity articleEntity;

  @override
  State<ArticleDetail> createState() => _ArticleDetailState();
}

class _ArticleDetailState extends State<ArticleDetail> {
  final _controllerDes = TextEditingController();
  List<ArticleCommentEntity> allComments = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CommonColor.colorF5,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          "帖子详情",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: Stack(
        children: [
          Positioned(
              top: 0.5,
              left: 0,
              right: 0,
              bottom: 64,
              child: ListView(
                children: [
                  _body(),
                  Divider(
                    thickness: 5,
                    height: 10,
                    color: CommonColor.colorF5,
                  ),
                  _comments(),
                  SizedBox(
                    height: 40,
                  )
                ],
              )),
          _bottomCart()
        ],
      ),
    );
  }

  _body() {
    var articleEntity = widget.articleEntity;
    ArticleExtraEntity? extra;
    List<dynamic> imgs = jsonDecode(articleEntity.image ?? '');
    if (articleEntity.extra?.isNotEmpty == true) {
      extra =
          ArticleExtraEntity.fromJson(jsonDecode(articleEntity.extra ?? ''));
    }

    List<dynamic>? comments =[];
    try {
      comments= jsonDecode(extra?.comment ?? '');
    } catch (e) {
      print(e);
    }
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(4)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              CachedNetworkImage(
                  imageBuilder: (context, image) => CircleAvatar(
                        backgroundImage: image,
                      ),
                  errorWidget: (context, url, error) => CircleAvatar(
                        backgroundImage: AssetImage(UserFeedBackImgs.user_male),
                      ),
                  width: 50,
                  height: 50,
                  imageUrl: UserFeedBackImgs.url + (extra?.profile ?? '')),
              SizedBox(
                width: 12,
              ),
              RichText(
                  text: TextSpan(children: [
                TextSpan(
                    text: (extra?.username ?? "姓名") + "\n",
                    style: TextStyle(
                        color: Color(0XFF333333), fontSize: 13, height: 2)),
                TextSpan(
                    text: extra?.time ?? "2202-10-11",
                    style: TextStyle(
                        color: Color(0XFF333333), height: 2, fontSize: 13))
              ]))
            ],
          ),
          Container(
            padding: EdgeInsets.all(6),
            margin: EdgeInsets.only(top: 6),
            decoration: BoxDecoration(
                color: Color(0XFFF1F1F1),
                borderRadius: BorderRadius.circular(4)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(articleEntity.title ?? "",
                    style: TextStyle(
                        color: Color(0XFF333333),
                        fontSize: 15,
                        fontWeight: FontWeight.w600)),
                SizedBox(
                  height: 4,
                ),
                Text(articleEntity.body ?? "",
                    style: TextStyle(
                      color: Color(0XFF666666),
                      fontSize: 14,
                    )),
                SizedBox(
                  height: 4,
                ),
                // RichText(
                //     text: TextSpan(children: [
                //   TextSpan(
                //       text: "请通过",
                //       style: TextStyle(
                //         color: Color(0XFF666666),
                //         fontSize: 13,
                //       )),
                //   TextSpan(
                //       text: extra?.contract ?? "1222202-10-11",
                //       style: TextStyle(
                //           color: Color(0XFF333333),
                //           fontWeight: FontWeight.w600,
                //           fontSize: 13)),
                //   TextSpan(
                //       text: "联系我，或者前往",
                //       style: TextStyle(color: Color(0XFF666666), fontSize: 13)),
                //   TextSpan(
                //       text: extra?.loc ?? "1222202-10-11",
                //       style: TextStyle(
                //           color: Color(0XFF333333),
                //           fontWeight: FontWeight.w600,
                //           fontSize: 13)),
                // ])),
                SizedBox(
                  height: 10,
                ),
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    childAspectRatio: 1,
                    crossAxisSpacing: 10,
                  ),
                  itemCount: imgs.length,
                  itemBuilder: (context, index) {
                    //   return Image.file(File(imgAD[index].path));
                    return _singleAD(UserFeedBackImgs.url + imgs[index]);
                  },
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
          SizedBox(
            height: 12,
          ),
          Row(
            children: [
              SizedBox(
                width: 20,
              ),
              Icon(
                Icons.comment,
                color: CommonColor.color99,
                size: 20,
              ),
              SizedBox(
                width: 6,
              ),
              Text((comments?.length ?? 0).toString()),
              Spacer(),
              Icon(
                Icons.favorite,
                color: QUtils.localLike(articleEntity.id ?? '')
                    ? Colors.red
                    : CommonColor.color99,
                size: 20,
              ),
              SizedBox(
                width: 6,
              ),
              GestureDetector(
                child: Text((articleEntity.like ?? 0).toString()),
                onTap: () => _like(articleEntity.id ?? ''),
              ),
              Spacer(),
              Icon(
                Icons.more_horiz,
                color: Colors.white,
                size: 20,
              ),
              SizedBox(
                width: 6,
              ),
            ],
          )
        ],
      ),
    );
  }

  _comments() {
    return ListView.separated(
      shrinkWrap: true,
      physics: new NeverScrollableScrollPhysics(),
      itemBuilder: (cxt, index) {
        var acti = allComments[index];
        return Container(
          color: Colors.white,
          padding: EdgeInsets.all(12),
          child: Row(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CachedNetworkImage(
                  imageBuilder: (context, image) => CircleAvatar(
                        backgroundImage: image,
                      ),
                  errorWidget: (context, url, error) => CircleAvatar(
                        backgroundImage: AssetImage(UserFeedBackImgs.user_male),
                      ),
                  width: 25,
                  height: 25,
                  imageUrl: UserFeedBackImgs.url + (acti.profile ?? '')),
              SizedBox(
                width: 10,
              ),
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Text(
                    acti.name ?? '',
                    style: TextStyle(fontSize: 12),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Text(
                    acti.time ?? '',
                    style: TextStyle(fontSize: 12, color: CommonColor.color99),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Text(
                    "说 \"" + (acti.content ?? '') + "\"",
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                  )
                ],
              ))
            ],
          ),
        );
      },
      separatorBuilder: (cxt, index) {
        return Divider(height: 1, color: CommonColor.colorF5);
      },
      itemCount: allComments.length,
    );
  }

  _bottomCart() {
    return Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: GestureDetector(
          child: Container(
            height: 64,
            decoration: const BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                    color: Colors.black12,
                    offset: Offset(0.0, 6.0),
                    blurRadius: 8,
                    spreadRadius: 4)
              ],
            ),
            child: Row(
              children: [
                const SizedBox(
                  width: 18,
                ),
                CachedNetworkImage(
                    imageBuilder: (context, image) => CircleAvatar(
                          backgroundImage: image,
                        ),
                    errorWidget: (context, url, error) => CircleAvatar(
                          backgroundImage:
                              AssetImage(UserFeedBackImgs.user_male),
                        ),
                    width: 35,
                    height: 35,
                    imageUrl: UserFeedBackImgs.url +
                        (SpUtil.getString("profile") ?? '')),
                const SizedBox(
                  width: 15,
                ),
                Text(
                  "添加评论",
                  style: TextStyle(fontSize: 18),
                ),
                const Spacer(),
                GestureDetector(
                  child: Icon(
                    Icons.favorite,
                    color: QUtils.localLike(widget.articleEntity.id ?? '')
                        ? Colors.red
                        : CommonColor.color99,
                    size: 30,
                  ),
                  onTap: () => _like(widget.articleEntity.id ?? ''),
                ),
                const SizedBox(
                  width: 18,
                )
              ],
            ),
          ),
          onTap: () {
            showBottomSheet();
          },
        ));
  }

  @override
  void initState() {
    super.initState();
    _addComment(false);
  }

  _updateComment() async {
    try {
      var art = widget.articleEntity;
      var res = await CommonClient().updateArticle(
          art.id ?? '',
          art.user ?? '',
          art.ty ?? 1,
          art.title ?? '',
          art.body ?? '',
          art.image ?? '',
          art.extra ?? '');
    } catch (e) {
      print(e);
    }
  }

  _like(String article) async {
    try {
      List<String> likes = [];
      try {
        var likeStr = SpUtil.getString("likeA") ?? '[]';
        List<dynamic> likeList = jsonDecode(likeStr);
        for (var element in likeList) {
          likes.add(element.toString());
        }
      } catch (e) {
        print(e);
      }
      if (likes.contains(article)) {
        var res =
            await CommonClient().unlike(SpUtil.getString("uid") ?? '', article);
        likes.remove(article);
        widget.articleEntity.like = (widget.articleEntity.like ?? 1) - 1;
      } else {
        var res =
            await CommonClient().like(SpUtil.getString("uid") ?? '', article);
        likes.add(article);
        widget.articleEntity.like = (widget.articleEntity.like ?? 0) + 1;
      }
      SpUtil.putString("likeA", jsonEncode(likes));
      setState(() {});
    } catch (e) {
      print(e);
    }
  }

  _singleAD(String pos) {
    return InstaImageViewer(
      child: CachedNetworkImage(
        width: 68,
        height: 68,
        fit: BoxFit.cover,
        alignment: Alignment.topCenter,
        imageUrl: pos,
      ),
    );
  }

  _addComment(bool up) {
    try {
      allComments.clear();
      var extra = ArticleExtraEntity.fromJson(
          jsonDecode(widget.articleEntity.extra ?? ''));
      List<dynamic>? comments = jsonDecode(extra.comment ?? '');
      comments?.forEach((element) {
        allComments.add(ArticleCommentEntity.fromJson(element));
      });
      allComments.sort((a, b) {
        return (b?.time ?? '').compareTo(a?.time ?? "");
      });
      setState(() {});
      if (up) _updateComment();
    } catch (e) {
      print(e);
    }
  }

  void showBottomSheet() {
    showModalBottomSheet(
      builder: (BuildContext context) {
        //构建弹框中的内容
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
          duration: const Duration(milliseconds: 100),
          child: Container(
            height: 200,
            padding: EdgeInsets.all(12),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      "评论",
                      style: TextStyle(
                          color: CommonColor.color33,
                          fontSize: 16,
                          fontWeight: FontWeight.w600),
                    ),
                    Spacer(),
                    GestureDetector(
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(vertical: 6, horizontal: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: CommonColor.colorMainGreen,
                            borderRadius: BorderRadius.circular(4)),
                        child: Text(
                          "发送",
                          style: TextStyle(
                              color: CommonColor.color33, fontSize: 14),
                        ),
                      ),
                      onTap: () {
                        if (_controllerDes.text.isEmpty) {
                          QmToast.toast('请输入评论内容');
                          return;
                        }
                        List<ArticleCommentEntity> comments = [];
                        var extra = ArticleExtraEntity.fromJson(
                            jsonDecode(widget.articleEntity.extra ?? ''));
                        try {
                          List<dynamic>? commentore =
                              jsonDecode(extra.comment ?? '');
                          commentore?.forEach((element) {
                            comments
                                .add(ArticleCommentEntity.fromJson(element));
                          });
                        } catch (e) {
                          print(e);
                        }
                        var comment = ArticleCommentEntity();
                        comment.time = QUtils.nowTimeStr();
                        comment.name = QUtils.getName();
                        comment.profile = QUtils.getProfile();
                        comment.content = _controllerDes.text;
                        comments.add(comment);
                        extra.comment = jsonEncode(comments);
                        widget.articleEntity.extra = jsonEncode(extra);
                        _controllerDes.clear();
                        try {
                          _addComment(true);
                        } catch (e) {
                          print(e);
                        } finally {
                          Get.back();
                        }
                      },
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Expanded(
                    child: TextField(
                  maxLines: 6,
                  maxLength: 140,
                  controller: _controllerDes,
                  decoration: const InputDecoration(
                    counterText: '',
                    contentPadding: EdgeInsets.fromLTRB(10, 0, 10, 15),
                    fillColor: Color(0x2083DF00),
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                      /*边角*/
                      borderRadius: BorderRadius.all(
                        Radius.circular(5), //边角为5
                      ),
                      borderSide: BorderSide(
                        color: Colors.white, //边线颜色为白色
                        width: 1, //边线宽度为2
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.white, //边框颜色为白色
                        width: 1, //宽度为5
                      ),
                      borderRadius: BorderRadius.all(
                        Radius.circular(5), //边角为30
                      ),
                    ),
                  ),
                )),
              ],
            ),
          ),
        );
      },
      context: context,
    );
  }
}
